package com.example.mininote;

import java.util.Timer;
import java.util.TimerTask;
import java.io.IOException;

import android.os.AsyncTask;
import android.view.KeyEvent;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;

//import com.example.mininote.GameView;
//import com.example.mininote.R;

public class NextxiActivity extends Activity implements OnClickListener {

    TextView score_show;
    private TextView startTime;
    private TextView countTime;
    private SeekBar seekBar;
    private Button play;
    private Button stop;
    private Button next;
    private Button last;
    private TextView tvState;
    private MediaPlayer player;
    private boolean playFlag = false,pauseFlag = false;

    GameView gv;
    TextView new_game;
    private Context mcontext=this;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            int num =msg.arg1;
            score_show.setText(num+"");
            player.start();
            handler.post(run);
//            onClick(View v);
        }

    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nextxi);
        initView();
        player=MediaPlayer.create(this, R.raw.celebration);//初始化音乐播放器
        seekBar.setMax(player.getDuration());//设最大值
        score_show = (TextView) findViewById(R.id.tv_score_show);
        gv =(GameView) findViewById(R.id.gv_show);
        new_game =(TextView) findViewById(R.id.tv_newgame);
        Button exitButton = (Button) findViewById(R.id.exit);
        new_game.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                gv.GameStart();
                gv.score = 0;

            }
        });

        exitButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                AlertDialog.Builder builder=new AlertDialog.Builder(mcontext);
                builder.setTitle("提示");
                builder.setMessage("确定要退出程序?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        System.exit(0);
                        finish();
                    }
                });
                builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();
            }
        });

        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                // TODO Auto-generated method stub
                if(fromUser){
                    player.seekTo(progress);
                }
            }
        });

        Timer timer =new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                Message msg = new Message();
                msg.arg1 = gv.score ;
                handler.sendMessage(msg);
            }
        }, 80, 150);
        score_show.setText(100+"");
    }
    private void initView() {
        // TODO Auto-generated method stub


        startTime=(TextView) findViewById(R.id.starttime);
        countTime=(TextView) findViewById(R.id.overtime);
        seekBar=(SeekBar) findViewById(R.id.seekbar);
        play=(Button) findViewById(R.id.stop);
        stop=(Button) findViewById(R.id.swit);
        next=(Button) findViewById(R.id.right);
        last=(Button) findViewById(R.id.left);

        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        next.setOnClickListener(this);
        last.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();//点击按钮的id
        switch (id) {
            case R.id.stop:
                player.start();
                handler.post(run);//开启

                break;
            case R.id.swit:
                player.stop();
                if(player.isPlaying())
                {
                    playFlag = false;
                    pauseFlag=true;
                    player.pause();
                    tvState.setText(getResources().getString(R.string.end));
                }
                try {
                    player.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();}

                break;
            case R.id.right:

                break;
            case R.id.left:

                break;
        }
    }

    Runnable run= new Runnable() {

        @Override
        public void run() {
            seekBar.setProgress(player.getCurrentPosition());//音乐播放器当前值
            setTime();
            handler.postDelayed(run, 200);//延时调用
        }
    };

    private class UpdateSeekBar extends AsyncTask<Integer,Integer,String> {
        @Override
        protected void onPostExecute(String s) {
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            seekBar.setProgress(values[0]);
        }
        @Override
        protected String doInBackground(Integer... params) {
            while(playFlag){
                try {
                    Thread.sleep(params[0]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.publishProgress(player.getCurrentPosition());
            }
            return null;
        }
    }

    private class MySeekBarChangeListener implements SeekBar.OnSeekBarChangeListener {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            player.seekTo(seekBar.getProgress());
        }
    }

    public void setTime(){//设置时间的方法
        int now =player.getCurrentPosition();//获取当前播放速度
        int count =player.getDuration();//获取总进度
        int second = now/1000;//当前有多少秒
        int csecond =count/1000;//总共有多少秒
        startTime.setText(second/60+":"+second%60);
        countTime.setText(csecond/60+":"+csecond%60);
    }
    @Override   //按键监听事件  keyCode是按下键的编码
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(keyCode==KeyEvent.KEYCODE_BACK){
            player.stop();
            player.release();//释放资源
            handler.removeCallbacks(run);//线程移除
            finish();		}
        return super.onKeyDown(keyCode, event);
    }


}
